package com.sky.jtail.controller;

import com.sky.jtail.domain.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


@Slf4j
@Component
public class WebSocketHandler extends TextWebSocketHandler {

    public Process process;


    public InputStream inputStream ;

    public InputStreamReader isReader ;

    public BufferedReader reader ;



    public TailThread thread  ;

    @Autowired
    private  static AppContainer appContainer;


    @Autowired
    public void setAppContainer(AppContainer appContainer) {
        WebSocketHandler.appContainer = appContainer;
    }

    @Autowired
    private  static FilesContainer filesContainer ;

    /**
     * 静态注入方式
     * @param filesContainer 文件容器
     */
    @Autowired
    public void setFilesContainer(FilesContainer filesContainer) {
        WebSocketHandler.filesContainer = filesContainer;
    }

    private  static WebSocketContainer webSocketContainer ;


    @Autowired
    public void setWsClientsContainer(WebSocketContainer webSocketContainer) {
        WebSocketHandler.webSocketContainer = webSocketContainer;
    }


    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        String fileKey = (String) session.getAttributes().get(AppConstant.fileKey);
        String wsAuth = (String) session.getAttributes().get(AppConstant.wsAuth);
        FileObject fileObject = appContainer.userFiles.get(wsAuth).get(fileKey);


        if(null == fileObject){
            session.sendMessage(new TextMessage("未选中文件！" + "<br>"));
            return;
        }
        webSocketContainer.put(fileKey,this);
        String cmd = "tail -f "+ fileObject.getFilePath();

        // 执行tail -f命令
        process = Runtime.getRuntime().exec(cmd);
        inputStream = process.getInputStream();


        // 启动新的线程，加载日志
        isReader = new InputStreamReader(inputStream);
        reader = new BufferedReader(isReader);
        thread = new TailThread(reader, session);
        thread.run();
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws IOException {
        log.info("已断开ws连接.");
        session.close();

    }



}